package com.bsoft.gol.hcs.his.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.*;
import com.bsoft.gol.hcs.clinical.bean.response.*;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.ParamsOrgQo;
import com.bsoft.gol.hcs.clinical.service.IMedicalSkillsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import com.bsoft.gol.hcs.enumcase.CheckEnum;
import hcn.base.CheckRequisitionDetail;
import hcn.base.CheckRequisitionRecord;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.bean.request.CheckSetDetailRequest;
import com.bsoft.gol.hcs.his.bean.request.CheckSetListRequest;
import com.bsoft.gol.hcs.his.bean.response.CheckSetDetailResponse;
import com.bsoft.gol.hcs.his.bean.response.CheckSetListResponse;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisXmlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.utils.*;
import org.atag.util.http.KdHttpClientUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.bsoft.gol.hcs.utils.CheckAppointmentUtil.getJsonDataFromHis;
import static com.bsoft.gol.hcs.utils.MapUtil.objectToMap;
import static com.bsoft.gol.hcs.utils.WhisClientUtil.*;

/**
 * @Description: 检查his服务(出入参xml格式)
 * @Author: zhaorb
 * @Date: 2020/6/4 15:08
 **/
@Service("medicalSkillsHisXmlService")
public class MedicalSkillsHisXmlService implements IMedicalSkillsHisXmlService {
    private final static Logger log = LoggerFactory.getLogger(MedicalSkillsHisXmlService.class);

    @Value("${whis_path_url}")
    public String WHIS_PATH_URL;

    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private IMedicalSkillsService medicalSkillsService;
    public static final String ORIGINORG = "1";

    @Value("${project_source}")
    private String proSource;

    @Override
    public BaseResponse<SaveCheckInfoRespFromHIS> saveCheckInfo(SaveCheckInfoReqForHIS saveCheckInfoReq) {
        log.info("=saveInspectionInfo-入参=>>>" + saveCheckInfoReq.toString() + "=====");
        BaseResponse<SaveCheckInfoRespFromHIS> result = new BaseResponse();


        return result;
    }

    @Override
    public BaseResponse returnInspectionItem(CancelMedicalSkillReq cancelMedicalSkillReq) {
        return null;
    }


    /**
     * @Description: 获得申请单号
     * @Author: zhaorb
     * @Date: 2020/6/6 14:55
     **/
    @Override
    public List<String> getApplyNo(ApplyNoRequest request) {
        log.info("getApplyNo-入参=>>>" + request.toString() + "=====");
        List<String> list = new ArrayList<>();
        String serviceName = "ODS_" + CheckEnum.GET_REQUEST_ID.getCode();
        String msgType = CheckEnum.GET_REQUEST_ID.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("VisitOrganization", request.getOrganizationId());
        queryConditions.put("RecordCount", request.getCount().toString());
        String requestCon = mapToXml(queryConditions, "Request");
        String queryConditionsXml = getMsgBody(requestCon);
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.getApplyNo入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject requestLists = data.getJSONArray("RequestLists").getJSONObject(0);
                JSONObject requestList = requestLists.getJSONArray("RequestList").getJSONObject(0);
                String requestId = requestList.get("RequestId").toString();
                list.add(requestId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    @Override
    public BaseResponse<CheckReportFormTotalReaponse> getCheckReportForm(CheckReportFormRequest request) {
        log.info("=CheckReportFormRequest-入参=>>>" + request.toString() + "=====");
        BaseResponse<CheckReportFormTotalReaponse> result = new BaseResponse();

        return result;
    }

    @Override
    public BaseResponse updateCheckItemStatus(CheckItemStatusRequest request) {
        return null;
    }

    /**
     * @Description: 检查提交xml
     * @Author: zhaorb
     * @Date: 2020/9/25 15:11
     **/
    @Override
    public SubmitMedicalSkillResponse submitMedicalSkillXml(SubmitMedicalSkillRequest request) {
        SubmitMedicalSkillResponse result = new SubmitMedicalSkillResponse();
        log.info("submitMedicalSkillXml-入参=>>>" + request.toString() + "=====");
        String serviceName = "ODS_" + CheckEnum.POST_APPLY_FORM.getCode();
        String msgType = CheckEnum.POST_APPLY_FORM.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG,proSource, msgType);
        //患者信息
        SubmitPatientRequest patientRequest = new SubmitPatientRequest();
        BeanUtils.copyProperties(request, patientRequest);
        patientRequest.setHospizationId("");
        Map<String, String> patientMap = objectToMap(patientRequest);
        String patientXml = mapToXmlWithEmptyValue(patientMap, "Patient");
        //visit信息
        SubmitVisitRequest visitRequest = new SubmitVisitRequest();
        BeanUtils.copyProperties(request, visitRequest);
        Map<String, String> visitMap = objectToMap(visitRequest);
        String visitXml = mapToXml(visitMap, "Visit");

        List<BaseHisPlateformClpInfoXmlRequest> clpInfos = new ArrayList<>();

        SubmitExamRequestRequest examRequestRequest = new SubmitExamRequestRequest();
        BeanUtils.copyProperties(request, examRequestRequest);
        Map<String, String> examRequestMap = objectToMap(examRequestRequest);

        List<ApplicationNoRequest> items = request.getItem();
        String itemListXml = "";
        for (ApplicationNoRequest noRequest : items) {
            Map<String, String> noRequestMap = objectToMap(noRequest);
            List<ExamItemsRequest> parts = noRequest.getParts();
            String partXml = "";
            for (ExamItemsRequest part : parts) {
                Map<String, String> partMap = objectToMap(part);
                partXml += mapToXml(partMap, "Parts");
            }
            noRequestMap.put("PartsList", partXml);
            noRequestMap.remove("Parts");
            itemListXml += mapToXml(noRequestMap, "Item");
        }

        //诊断信息
        List<SubmitDiagnoseRequest> diagnoseRequests = request.getDiagnoseRequests();
        String diagnoseXml = "";
        if (CommonUtils.isNotEmpty(diagnoseRequests)) {
            for (SubmitDiagnoseRequest sdr : diagnoseRequests) {
                Map<String, String> diagnoseReqMap = objectToMap(sdr);
                diagnoseXml += mapToXml(diagnoseReqMap, "Diagnose");
            }
        }
        examRequestMap.put("DiagnoseList", diagnoseXml);
        examRequestMap.put("ItemList", itemListXml);
        examRequestMap.put("RequestDateTime", DateUtil.format5.format(new Date()));
        String examRequestXml = mapToXml(examRequestMap, "ExmRequest");

        String clpInfoXml = "<ClpInfos>";
        List<BaseHisPlateformClpInfoXmlRequest> clpInfoXmlRequests = request.getClpInfoXmlRequests();
        if(CommonUtils.isNotEmpty(clpInfoXmlRequests)){
            for (BaseHisPlateformClpInfoXmlRequest clpInfoXmlRequest : clpInfoXmlRequests) {
                Map<String, String> clpInfoMap = objectToMap(clpInfoXmlRequest);
                clpInfoXml += mapToXmlWithEmptyValue(clpInfoMap, "ClpInfo");
            }
            clpInfoXml += "</ClpInfos>";
        }

        String queryConditionsXml = getMsgBody(patientXml + clpInfoXml + visitXml + examRequestXml);
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.submitMedicalSkillXml入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                if (CommonUtils.isEmpty(msgBody.getString("Data"))) {
                    return result;
                }

                //医技申请费用主表
                List<SubmitMedicalSkillDetail> details = new ArrayList<>();
                //申请单的费用明细
                List<SubmitMedicalSkillDetail.ExpenseRecord> records = new ArrayList<>();

                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                //遍历his返回的费用列表
                JSONArray expenses = data.getJSONArray("ExpenseLists");
                if (CommonUtils.isNotEmpty(expenses)) {
                    JSONObject expenseLists = data.getJSONArray("ExpenseLists").getJSONObject(0);
                    for (int k = 0; k < expenses.size(); k++) {
                        JSONObject expenseList = expenseLists.getJSONArray("ExpenseList").getJSONObject(k);
                        String requestId = expenseList.get("RequestId").toString();
                        String itemId = expenseList.get("ItemId").toString();
                        String itemName = expenseList.get("ItemName").toString();
                        //his的的医技序号
                        String expenseId = expenseList.get("ExpenseId").toString();
                        String totalCost = expenseList.get("TotalCost").toString();
                        SubmitMedicalSkillDetail skillDetail = new SubmitMedicalSkillDetail();
                        skillDetail.setAmount(BigDecimal.valueOf(Double.parseDouble(totalCost)));
                        skillDetail.setApplicationNo(requestId);
                        skillDetail.setExpenseId(expenseId);
                        skillDetail.setItemId(itemId);
                        skillDetail.setItemName(itemName);
                        JSONObject expenseDetailLists = expenseList.getJSONArray("ExpenseDetailLists").getJSONObject(0);
                        JSONArray detailList = expenseDetailLists.getJSONArray("ExpenseDetailList");
                        for (int i = 0; i < detailList.size(); i++) {
                            String expenseDetailId = detailList.getJSONObject(i).get("ExpenseDetailId").toString();
                            String costId = detailList.getJSONObject(i).get("CostId").toString();
                            String costName = detailList.getJSONObject(i).get("CostName").toString();
                            String costNumber = detailList.getJSONObject(i).get("CostNumber").toString();
                            String costUnit = detailList.getJSONObject(i).get("CostUnit").toString();
                            String costPrice = detailList.getJSONObject(i).get("CostPrice").toString();
                            String costSubtotal = detailList.getJSONObject(i).get("CostSubtotal").toString();
                            SubmitMedicalSkillDetail.ExpenseRecord record = new SubmitMedicalSkillDetail.ExpenseRecord();
                            record.setAmount(BigDecimal.valueOf(Double.parseDouble(costSubtotal)));
                            record.setPrice(BigDecimal.valueOf(Double.parseDouble(costPrice)));
                            record.setUnit(costUnit);
                            record.setNumber(costNumber);
                            record.setExpenseDetailId(expenseDetailId);
                            record.setItemId(costId);
                            record.setItemName(costName);
                            records.add(record);
                        }
                        skillDetail.setApplicationDetailList(records);
                        details.add(skillDetail);
                    }
                }

                result.setApplicationList(details);
                result.setMessage("提交成功");
                return result;
            } else {
                result.setMessage(msgBody.get("Detail").toString());
                result.setCode(ResultCode.ERROR);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(ExceptionMessageUtil.operateHisErrorMessage(e.getMessage()));
            result.setCode(ResultCode.ERROR);
            return result;
        }
    }

    /**
     * @Description: 检查单撤回
     * @Author: zhaorb
     * @Date: 2020/11/9 19:33
     **/
    @Override
    public BaseResponse updateCheckInfo(CheckRequisitionRecord record, List<CheckRequisitionDetail> details, String examStatusCode, String invoiceNo, String itemCost) {
        BaseResponse<List<OrganizeListResponse>> baseResponse = new BaseResponse<>();
        String serviceName = "ODS_" + CheckEnum.UPDATE_APPLY_FORM.getCode();
        String msgType = CheckEnum.UPDATE_APPLY_FORM.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, proSource, msgType);
        //患者信息
        Map<String, String> patientMap = new HashMap<>(4);
        patientMap.put("SourcePatientId", record.getPatientId());
        patientMap.put("DomainId", "1");
        String patientXml = mapToXml(patientMap, "Patient");
        //visit信息
        Map<String, String> visitMap = new HashMap<>(4);
        visitMap.put("VisitId", "1");
        visitMap.put("VisitTimes", "1");
        String visitXml = mapToXml(visitMap, "Visit");
        //检查状态信息
        Map<String, String> statusMap = new HashMap<>(4);
        statusMap.put("RequestId", record.getApplicationNo());
        //开单机构
        if (Constants.GOL.equals(proSource)) {
            //localorgid
            ParamsOrgQo qo = new ParamsOrgQo();
            qo.setOrgId(record.getOpenOrgId());
            List<Map> maps = (List<Map>) baseDataService.queryOrganizationList(qo).getData();
            if (CommonUtils.isNotEmpty(maps)) {
                statusMap.put("VisitOrganization", maps.get(0).get("organizationId").toString());
            } else {
                return BaseRespUtil.setResultError("开单机构id不能为空");
            }
        } else {
            statusMap.put("VisitOrganization", record.getOpenOrgId());
        }
        String majorItemId = details.get(0).getExamMajorItemId();
        //检查申请项目
        Map<String, String> majorMap = new HashMap<>(4);
        majorMap.put("ItemCode", majorItemId);
        majorMap.put("ExamStatusCode", examStatusCode);
        if (CommonUtils.isNotEmpty(invoiceNo)) {
            majorMap.put("InvoiceNo", invoiceNo);
            majorMap.put("ItemCost", itemCost);
        }
        String majorXml = mapToXml(majorMap, "Item");
        statusMap.put("ItemList", majorXml);
        String statusXml = mapToXml(statusMap, "ExamStatusInfo");

        String queryConditionsXml = getMsgBody(patientXml + visitXml + statusXml);
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.updateCheckInfo入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                baseResponse.setMessage(msgBody.getString("Detail"));
            } else {
                baseResponse = BaseRespUtil.setResultError(msgBody.getString("Detail"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");

        }
        log.info("MedicalSkillsHisXmlService.getOrganizeList出参：{}", baseResponse);
        return baseResponse;
    }


    @Override
    public BaseResponse<List<QueryCheckItemDtailResp>> queryCheckItemDtail(QueryCheckItemDtailReq request) {
        return null;
    }

    @Override
    public BaseResponse<QueryMedicalSkillListRespFromHIS> queryMedicalSkillList(QueryMedicalSkillListReqForHIS queryMedicalSkillListReq) {
        return null;
    }


    /**
     * @Description: 获得检查机构列表xml
     * @Author: zhaorb
     * @Date: 2020/9/3 15:24
     **/
    @Override
    public BaseResponse<List<OrganizeListResponse>> getOrganizeList() {
        BaseResponse<List<OrganizeListResponse>> baseResponse = new BaseResponse<>();
        List<OrganizeListResponse> organizeList = new ArrayList<>();
        String serviceName = "ODS_" + CheckEnum.GET_ORGANIZE_LIST.getCode();
        String msgType = CheckEnum.GET_ORGANIZE_LIST.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG,proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        String queryConditionsXml = mapToXml(queryConditions, "MsgBody");
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.getOrganizeList入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject examExecuteOrgs = data.getJSONArray("ExamExecuteOrgs").getJSONObject(0);
                JSONArray examExecuteOrg = examExecuteOrgs.getJSONArray("ExamExecuteOrg");
                List<OrganizionResponse> list = JSONObject.parseArray(examExecuteOrg.toJSONString(),
                        OrganizionResponse.class);
                for (OrganizionResponse organizion : list) {
                    OrganizeListResponse ol = new OrganizeListResponse();
                    ol.setOrganizationId(organizion.getExamExecuteOrgId());
                    ol.setOrganizationName(organizion.getExamExecuteOrgName());
                    organizeList.add(ol);
                }
                baseResponse.setData(organizeList);
            } else {
                baseResponse = BaseRespUtil.setResultError(msgBody.getString("Detail"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");

        }
        log.info("MedicalSkillsHisXmlService.getOrganizeList出参：{}", baseResponse);
        return baseResponse;
    }

    @Override
    public BaseResponse<CheckTypeTotalResponse> queryCheckTypeList(CheckTypeRequest request) {
        log.info("=queryCheckTypeList-入参=>>>" + request.toString() + "=====");
        BaseResponse<CheckTypeTotalResponse> baseResponse = new BaseResponse();
        CheckTypeTotalResponse checkTypeTotalResponse = new CheckTypeTotalResponse();
        String serviceName = "ODS_" + CheckEnum.GET_EXAM_TYPE_LIST.getCode();
        String msgType = CheckEnum.GET_EXAM_TYPE_LIST.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG,proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("ExamExecuteOrgId", request.getOrganizationId());
        String queryConditionsXml = mapToXml(queryConditions, "MsgBody");
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.queryCheckTypeList 入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject examTypes = data.getJSONArray("ExamTypes").getJSONObject(0);
                JSONArray examType = examTypes.getJSONArray("ExamType");
                List<CheckTypeResponseTemp> list = JSONObject.parseArray(examType.toJSONString(),
                        CheckTypeResponseTemp.class);
                checkTypeTotalResponse.setTotal(list.size());
                List<CheckTypeResponse> checks = new ArrayList<>();
                List<OrganizeListResponse> organizeList = getOrganizeList().getData();
                List<OrganizeListResponse> filter = organizeList.stream()
                        .filter(organize -> request.getOrganizationId().equals(organize.getOrganizationId()))
                        .collect(Collectors.toList());
                if (CommonUtils.isNotEmpty(filter)) {
                    OrganizeListResponse organize = filter.get(0);
                    for (CheckTypeResponseTemp temp : list) {
                        CheckTypeResponse response = new CheckTypeResponse();
                        response.setExamTypeId(temp.getExamTypeCode());
                        response.setPyCode(temp.getPyCode());
                        response.setExamTypeName(temp.getExamTypeName());
                        response.setOrganizationId(request.getOrganizationId());
                        response.setOrganizationName(organize.getOrganizationName());
                        checks.add(response);
                    }

                }
                checkTypeTotalResponse.setList(checks);
                baseResponse.setData(checkTypeTotalResponse);
            } else {
                baseResponse = BaseRespUtil.setResultError(msgBody.getString("Detail"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");

        }
        log.info("MedicalSkillsHisXmlService.queryCheckTypeList出参：{}", baseResponse);
        return baseResponse;
    }

    /**
     * @Description: 获取检查单项目列表
     * @Author: zhaorb
     * @Date: 2020/6/4 15:24
     **/
    @Override
    public List<QueryCheckItemListResp> queryCheckItemList(QueryCheckItemListReq request) {
        log.info("=queryCheckItemList-入参=>>>" + request.toString() + "=====");
        String serviceName = "ODS_" + CheckEnum.GET_EXAM_MAJOR_ITEM_LIST.getCode();
        String msgType = CheckEnum.GET_EXAM_MAJOR_ITEM_LIST.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG,proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("ExamExecuteOrgId", request.getOrganizationId());
        if (CommonUtils.isNotEmpty(request.getExamTypeId())) {
            queryConditions.put("ExamTypeCode", request.getExamTypeId());
        }
        String queryConditionsXml = mapToXml(queryConditions, "MsgBody");
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.queryCheckItemList 入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject majorItems = data.getJSONArray("ExamMajorItems").getJSONObject(0);
                JSONArray majorItem = majorItems.getJSONArray("ExamMajorItem");
                List<QueryCheckItemListRespTemp> list = JSONObject.parseArray(majorItem.toJSONString(),
                        QueryCheckItemListRespTemp.class);
                List<QueryCheckItemListResp> checks = new ArrayList<>();
                CheckTypeRequest ct = new CheckTypeRequest();
                ct.setOrganizationId(request.getOrganizationId());
                List<CheckTypeResponse> cts = queryCheckTypeList(ct).getData().getList();
                List<CheckTypeResponse> resCts = new ArrayList<>();
                if (CommonUtils.isNotEmpty(request.getExamTypeId())) {
                    resCts = cts.stream()
                            .filter(ctr -> request.getExamTypeId().equals(ctr.getExamTypeId()))
                            .collect(Collectors.toList());
                }else{
                    resCts.addAll(cts);
                }
                if (CommonUtils.isNotEmpty(resCts)) {
                    CheckTypeResponse typeResponse = resCts.get(0);
                    for (QueryCheckItemListRespTemp temp : list) {
                        QueryCheckItemListResp response = new QueryCheckItemListResp();
                        response.setExamMajorItemId(temp.getExamMajorItemCode());
                        response.setPyCode(temp.getPyCode());
                        response.setExamMajorItemName(temp.getExamMajorItemName());
                        response.setExecuteDepartmentId(temp.getExecuteDepartmentId());
                        response.setExecuteDepartmentName(temp.getExecuteDepartmentName());
                        response.setOrganizationId(typeResponse.getOrganizationId());
                        response.setOrganizationName(typeResponse.getOrganizationName());
                        response.setExamTypeId(typeResponse.getExamTypeId());
                        response.setExamTypeName(typeResponse.getExamTypeName());
                        checks.add(response);
                    }
                }
                return checks;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    /**
     * @Description: 获取项目部位和方法（HIS）
     * @Author: xuxy
     * @Date: 2020/6/4 16:12
     **/
    @Override
    public List<QueryCheckPositionItemResp> queryCheckPositionList(QueryCheckPositionListReq request) {
        log.info("=queryCheckPositionList-入参=>>>" + request.toString() + "=====");
        List<QueryCheckPositionItemResp> resps = new ArrayList<>();
        String serviceName = "ODS_" + CheckEnum.GET_EXAM_ITEM_LIST.getCode();
        String msgType = CheckEnum.GET_EXAM_ITEM_LIST.getValue();
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG,proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("ExamExecuteOrgId", request.getOrganizationId());
        queryConditions.put("ExamTypeCode", request.getExamTypeId());
        queryConditions.put("ExamMajorItemCode", request.getExamMajorItemId());
        String queryConditionsXml = mapToXml(queryConditions, "MsgBody");
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        log.info("MedicalSkillsHisXmlService.queryCheckPositionList 入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {//返回成功
                JSONObject data = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject examItems = data.getJSONArray("ExamItems").getJSONObject(0);
                JSONArray examItem = examItems.getJSONArray("ExamItem");
                List<QueryCheckPositionItemRespTemp> list = JSONObject.parseArray(examItem.toJSONString(),
                        QueryCheckPositionItemRespTemp.class);
                if (CommonUtils.isNotEmpty(list)) {
                    for (QueryCheckPositionItemRespTemp temp : list) {
                        QueryCheckPositionItemResp resp = new QueryCheckPositionItemResp();
                        BeanUtils.copyProperties(temp, resp);
                        resp.setExamItemId(temp.getExamItemCode());
                        List<QueryCheckExamMethodsResp> examMethodsResps = new ArrayList<>();
                        QueryCheckExamMethodsResp examMethodsResp = new QueryCheckExamMethodsResp();
                        examMethodsResp.setExamMethodId(temp.getExamMethodCode());
                        examMethodsResp.setExamMethodName(temp.getExamMethodName());
                        examMethodsResps.add(examMethodsResp);
                        resp.setExamMethods(examMethodsResps);
                        resps.add(resp);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resps;
    }

    @Override
    public BaseResponse<CheckReportInfoTotalResp> getCheckReportInfo(CheckReportInfoReq request) {
        log.info("=CheckReportInfoReq-入参=>>>" + request.toString() + "=====");
        BaseResponse<CheckReportInfoTotalResp> baseResponse = new BaseResponse();
        String serviceName = Constants.GET_REPORT_INFO;
        String msgHeaderXml = getHeaderXml();
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("pageSize", request.getPageSize().toString());
        String queryConditionsXml = mapToXml(queryConditions, "Item");
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromHis(WHIS_PATH_URL, serviceName, msgHeaderXml,
                    queryConditionsXml);
            JSONObject msgHeaderJson = jsonObjectBSXml.getJSONArray("MsgHeader").getJSONObject(0);
            if ("true".equals(msgHeaderJson.getString("Status"))) {//返回成功
                JSONObject itemJsonObject = jsonObjectBSXml.getJSONArray("Item").getJSONObject(0);
                CheckReportInfoTotalResp resp = JSONObject.parseObject(itemJsonObject.toJSONString(),
                        CheckReportInfoTotalResp.class);
                baseResponse.setData(resp);
            } else {
                baseResponse = BaseRespUtil.setResultError(msgHeaderJson.getString("Detail"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");

        }
        log.info("MedicalSkillsHisXmlService.getOrganizeList出参：{}", baseResponse);
        return baseResponse;
    }

    /**
     * 查询组套列表
     * @param request
     * @return
     */
    @Override
    public CheckSetListResponse queryCheckSetList(CheckSetListRequest request) {
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = Constants.COMMON_PROXY_URL + Constants.QUERY_CHECK_SET_LIST;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        if(null != jsonObject && null != jsonObject.getJSONObject("data")){
            CheckSetListResponse result = JSON.parseObject(jsonObject.getJSONObject("data").toJSONString(),CheckSetListResponse.class);
            return result;
        }
        return null;
    }

    /**
     * 查询组套详情
     * @param request
     * @return
     */
    @Override
    public CheckSetDetailResponse queryCheckSetDetail(CheckSetDetailRequest request) {
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        String url = Constants.COMMON_PROXY_URL + Constants.QUERY_CHECK_SET_DETAIL;
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
        if(null != jsonObject && null != jsonObject.getJSONObject("data")){
            CheckSetDetailResponse result = JSON.parseObject(jsonObject.getJSONObject("data").toJSONString(),CheckSetDetailResponse.class);
            return result;
        }
        return null;
    }
}
